<?php

defined('BASEPATH') or die('forbidden');

/**
 * 判断是否是会员
 */
function check_login() {
    $framework = &get_instance('controller');
    return $framework->auth->check_level(1);
}

/**
 * 前台检查会员权限
 * @param string $rank 等级
 * @param string $catalog 栏目
 * @param string $action 动作
 */
function check_level($rank = 1, $catalog = null, $action = null) {
    $framework = &get_instance('controller');
    if (!$framework->auth->is_login()) {
        $seg0 = segment(0);
        $mobile = $seg0 == 'mobile' ? "/mobile" : '';
        header("location:{$mobile}/user/login/?url=" . current_url());
    }
    if (!$framework->auth->check_level($rank, $catalog, $action))
        error("你没有权限浏览该页面!", -1, 2000);
}

/**
 * 温馨错误提示
 * @param string $title 标题
 * @param string $message 错误详细内容 
 */
function tips($title = '', $message = '') {
    $framework = &get_instance('controller');
    $res_url = $framework->config['res_url'];
    include APPPATH . 'errors/error_tips.php';
    exit;
}

/**
 * 渲染到模板
 * @param string $tpl
 * @param array $data
 */
function render($tpl, $data = array()) {
    $framework = &get_instance('controller');
    if (is_ajax()) {
        if ($tpl == 'error') {
            json_output(-1, $data);
        } else {
            $framework->view->display($tpl, $data);
        }
    } else {
        if ($tpl == 'error') {
            $data = array('msg' => $data);
        }
        $framework->view->assign("familybill", $framework->bill->get_family_combine());
        $framework->view->assign("module", $tpl);
        $seg0 = segment(0);
        $mobile = $seg0 == 'mobile' ? "mobile/" : '';
        $framework->view->display("{$mobile}template", $data);
    }
}

/**
 * 判断玩家是否属于指定ID
 * @param int $user_id 会员ID
 * @param int $family_id 家庭组ID
 * @return boolean
 */
function check_in_family($user_id = null, $family_id = null) {
    if (!$user_id || !$family_id) {
        $framework = &get_instance('controller');
        $user_id = !$user_id ? $framework->db->user_id : $user_id;
        $family_id = !$family_id ? $framework->auth->fields['family_id'] : $family_id;
    }
    $family = $framework->family->get_family_ids($family_id);
    if (in_array($user_id, $family)) {
        return true;
    } else {
        return false;
    }
}

function login_failure($username, $password, $intro) {
    $framework = &get_instance('controller');
    $ip = get_ip();
    $time = time();
    $framework->db->insert("{pre}login_failure", array('username' => $username, 'password' => $password, 'intro' => $intro, 'ip' => $ip, 'createtime' => $time));
}

/**
 * 读取指定分类数据
 * @param int $id
 * @return array
 */
function get_category($id) {
    $framework = &get_instance('controller');
    return $framework->category->get_category($id);
}

function get_account($id) {
    $framework = &get_instance('controller');
    return $framework->account->get_account($id);
}

function get_category_list($type = 'expense', $father_id = 0, $first = null, $user_id = null) {
    $framework = &get_instance('controller');
    $result = array();
    $list = $framework->category->get_category_list($type, $father_id, $user_id);
    if ($first && is_array($first)) {
        foreach ($first as $m => $n) {
            $result[$m] = $n;
        }
    }
    foreach ($list as $k => $v) {
        if (!$v['state'])
            continue;
        $result[$v['id']] = $v;
    }
    return $result;
}

/**
 * 读取一级分类列表option数据
 * @param string $type 类型名称
 * @param int $father_id 父ID
 * @param mixed $selected 选中项
 * @param mixed $first 前置数据
 * @param int $user_id 会员ID
 * @return array
 */
function get_category_option($type = 'expense', $father_id = 0, $selected = null, $first = null, $user_id = null) {
    $framework = &get_instance('controller');
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $result = array();
    $list = $framework->category->get_category_list($type, $father_id, $user_id);
    if ($first && is_array($first)) {
        foreach ($first as $m => $n) {
            $text = in_array($m, $selected) ? " selected" : '';
            $result[] = "<option value='{$m}'>{$n}</option>";
        }
    }
    foreach ($list as $k => $v) {
        if (!$v['state'])
            continue;
        $text = in_array($v['id'], $selected) ? " selected" : '';
        $result[] = "<option value='{$v['id']}'{$text}>{$v['name']}</option>";
    }
    return implode("\n", $result);
}

/**
 * 读取二级分类列表数组
 * @param string $type 类型名称
 * @param int $user_id 会员ID
 * @return array
 */
function get_category_list_full($type = 'expense', $showhidden = false, $user_id = null) {
    $framework = &get_instance('controller');
    $user_id = $user_id ? $user_id : $framework->auth->user_id;
    $list = array();
    if ($type == 'borrow') {
        $arr = get_borrow_category_list();
        foreach ($arr as $m => $n) {
            $list[$m] = array('id' => $m, 'name' => $n, 'sons' => array(), 'father_id' => 0, 'state' => 1, 'user_id' => $user_id);
        }
    } else {
        foreach ($framework->category->usercategory as $m => $n) {
            if ($n['type'] != $type || ($user_id > 0 && $user_id != $n['user_id']))
                continue;
            if (!$showhidden && !$n['state'])
                continue;
            if ($n['father_id'] == 0) {
                $n['sons'] = array();
                $list[$n['id']] = $n;
            }
        }
        foreach ($framework->category->usercategory as $m => $n) {
            if ($n['type'] != $type || ($user_id > 0 && $user_id != $n['user_id']) || !isset($list[$n['father_id']]))
                continue;
            if (!$showhidden && !$n['state'])
                continue;
            if ($n['father_id'] > 0) {
                $list[$n['father_id']]['sons'][$n['id']] = $n;
            }
        }
    }
    return $list;
}

/**
 * 读取二级分类列表option数据
 * @param string $type 类型名称
 * @param mixed $selected 选中项
 * @param int $user_id 会员ID
 * @return array
 */
function get_category_option_full($type = 'expense', $selected = null, $user_id = null) {
    $framework = &get_instance('controller');
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $user_id = $user_id ? $user_id : $framework->auth->user_id;
    $list = array();
    foreach ($framework->category->usercategory as $m => $n) {
        if ($n['type'] != $type || ($user_id > 0 && $user_id != $n['user_id']) || !$n['state'])
            continue;
        if ($n['father_id'] == 0) {
            $list[$n['id']] = array('id' => $n['id'], 'name' => $n['name'], 'sons' => array());
        }
    }
    foreach ($framework->category->usercategory as $m => $n) {
        if ($n['type'] != $type || ($user_id > 0 && $user_id != $n['user_id']) || !$n['state'] || !isset($list[$n['father_id']]))
            continue;
        if ($n['father_id'] > 0) {
            $list[$n['father_id']]['sons'][$n['id']] = $n['name'];
        }
    }
    $result = array();
    foreach ($list as $m => $n) {
        $result[] = "<optgroup label='{$n['name']}' rel='{$n['id']}'>";
        foreach ($n['sons'] as $u => $v) {
            $text = in_array($u, $selected) ? " selected" : '';
            $result[] = "<option value='{$u}'{$text}>{$v}</option>";
        }
        $result[] = "</optgroup>";
    }
    return implode("\n", $result);
}

function init_category($user_id = null) {
    $framework = &get_instance('controller');
    $user_id = $user_id ? $user_id : $framework->auth->user_id;
    $out = array(
        1 => array('name' => '衣', 'son' => array('购衣费', '化妆品', '洗衣费用', '箱包', '饰品')),
        2 => array('name' => '食', 'son' => array('外出就餐', '工作餐', '买菜', '柴米油盐', '外卖', '零食', '小吃', '饮料', '水果', '烟酒茶')),
        3 => array('name' => '住', 'son' => array('水电气费', '房租', '物业费')),
        4 => array('name' => '行', 'son' => array('停车费', '汽油费用', '公共交通', '的士费用', '汽车保养', '过路费', '年检保险', '违章罚款', '汽车修理')),
        5 => array('name' => '教育', 'son' => array('书籍杂志', '文具费用', '考试费用', '培训费用', '学杂费用')),
        6 => array('name' => '娱乐', 'son' => array('旅游度假', '休闲放松', '博彩支出', '健身运动', '宠物饲养')),
        7 => array('name' => '医疗', 'son' => array('诊疗费', '药品费', '健康食品')),
        9 => array('name' => '其它', 'son' => array('话费', '网费', '电器用品', '生活用品', '洗衣费用', '保险费用', '税收费用', '交际费用', '孝敬长辈', '捐款捐赠', '坏账损失')),
    );

    $in = array(
        1 => array('name' => '薪资', 'son' => array('公司工资', 'SOHO接单', '加班收入', '奖金')),
        3 => array('name' => '投资', 'son' => array('股票', '基金', '分红', '利息')),
        4 => array('name' => '其它', 'son' => array('发票中奖', '博彩收入', '分红', '利息', '其它')),
    );
    foreach ($out as $m => $n) {
        $data = array('uuid' => get_uuid(), 'user_id' => $user_id, 'father_id' => 0,
            'name' => $n['name'], 'type' => 'expense', 'createtime' => TIME, 'modifytime' => TIME,
            'rank' => $m,
        );
        $id = $framework->db->insert("{pre}category", $data);
        foreach ($n['son'] as $k => $v) {
            $data = array('uuid' => get_uuid(), 'user_id' => $user_id, 'father_id' => $id,
                'name' => $v, 'type' => 'expense', 'createtime' => TIME, 'modifytime' => TIME,
                'rank' => $k + 1,
            );
            $framework->db->insert("{pre}category", $data);
        }
    }

    foreach ($in as $m => $n) {
        $data = array('uuid' => get_uuid(), 'user_id' => $user_id, 'father_id' => 0,
            'name' => $n['name'], 'type' => 'income', 'createtime' => TIME, 'modifytime' => TIME,
            'rank' => $m,
        );
        $id = $framework->db->insert("{pre}category", $data);
        foreach ($n['son'] as $k => $v) {
            $data = array('uuid' => get_uuid(), 'user_id' => $user_id, 'father_id' => $id,
                'name' => $v, 'type' => 'income', 'createtime' => TIME, 'modifytime' => TIME,
                'rank' => $k + 1,
            );
            $framework->db->insert("{pre}category", $data);
        }
    }
}

function get_account_list($type = null, $first = null, $user_id = null) {
    $framework = &get_instance('controller');
    $type = is_array($type) ? $type : ($type ? array($type) : array());
    $result = array();
    $list = $framework->account->get_account_list($type, $user_id);
    if ($first && is_array($first)) {
        foreach ($first as $m => $n) {
            $result[] = $n;
        }
    }
    foreach ($list as $k => $v) {
        if ($type && !in_array($v['type'], $type))
            continue;
        if (!$v['state'])
            continue;
        $result[] = $v;
    }
    return $result;
}

/**
 * 读取账户option列表
 * @param mixed $type 账户类型
 * @param mixed $selected 选中项
 * @param mixed $first 前置追加项
 * @param int $user_id 会员ID
 * @return array
 */
function get_account_option($type = null, $selected = null, $first = null, $user_id = null) {
    $framework = &get_instance('controller');
    $type = is_array($type) ? $type : ($type ? array($type) : array());
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $result = array();
    $list = $framework->account->get_account_list($type, $user_id);
    if ($first && is_array($first)) {
        foreach ($first as $m => $n) {
            $text = in_array($m, $selected) ? " selected" : '';
            $result[] = "<option value='{$m}'>{$n}</option>";
        }
    }
    if (!$list && !$first) {
        $list[] = array('id' => '', 'name' => '请添加账户', 'type' => $type[0], 'state' => 1);
    }
    foreach ($list as $k => $v) {
        if ($type && !in_array($v['type'], $type))
            continue;
        if (!$v['state'])
            continue;
        $text = in_array($v['id'], $selected) ? " selected" : '';
        $result[] = "<option value='{$v['id']}'{$text}>{$v['name']}</option>";
    }
    return implode("\n", $result);
}

function get_account_type_option($selected = null) {
    $framework = &get_instance('controller');
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $result = array();
    foreach ($framework->account->account_type as $k => $v) {
        $text = in_array($k, $selected) ? " selected" : '';
        $result[] = "<option value='{$k}'{$text}>{$v}</option>";
    }
    return implode("\n", $result);
}

function get_account_currency_option($selected = null) {
    $framework = &get_instance('controller');
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $result = array();
    foreach ($framework->account->account_currency as $k => $v) {
        $text = in_array($v['id'], $selected) ? " selected" : '';
        $result[] = "<option value='{$v['id']}'{$text}>{$v['name']}</option>";
    }
    return implode("\n", $result);
}

function get_bank_option($selected = null) {
    $framework = &get_instance('controller');
    $selected = is_array($selected) ? $selected : ($selected ? array($selected) : array());
    $banklist = $framework->cache->get("banklist");
    if (!$banklist) {
        $banklist = $framework->db->simple("SELECT * FROM {pre}bank WHERE state='1' ORDER BY weigh ASC");
        $framework->cache->set("banklist", $banklist);
    }
    $result = array();
    foreach ($banklist as $k => $v) {
        $text = in_array($v['id'], $selected) ? " selected" : '';
        $result[] = "<option value='{$v['id']}'{$text}>{$v['name']}</option>";
    }
    return implode("\n", $result);
}

function get_bill_type() {
    return array('expense' => '支出', 'income' => '收入', 'transfer' => '转账', 'borrow' => '借款/报销', 'credit' => '信用卡还款');
}

function get_bill_type_name($type) {
    $arr = get_bill_type();
    return isset($arr[$type]) ? $arr[$type] : $arr['expense'];
}

function get_borrow_category_name($category_id = 0) {
    $arr = get_borrow_category_list();
    return isset($arr[$category_id]) ? $arr[$category_id] : '未知';
}

function get_borrow_category_list() {
    return array(1 => '借出', 2 => '借入', 3 => '还入', 4 => '还出');
}

function get_notice_list($pagesize = 10) {
    $framework = &get_instance('controller');
    $allnotice = $framework->cache->get("notice_list");
    if (!$allnotice) {
        $allnotice = array();
        $framework->db->query("SELECT * FROM {pre}notice WHERE state>0 ORDER BY weigh DESC");
        while ($row = $framework->db->get_array()) {
            $allnotice[] = $row;
        }
        $framework->cache->set("notice_list", $allnotice);
    }
    $time = time();
    foreach ($allnotice as $m => $n) {
        if (($n['starttime'] > 0 && $n['starttime'] > $time) || ($n['expiretime'] > 0 && $n['expiretime'] < $time))
            unset($allnotice[$m]);
    }
    return array_slice($allnotice, 0, $pagesize);
}

function get_frequency_list() {
    return array(
        'everyday' => '每天',
        'workday' => '工作日',
        'workday_fd' => '工作日(除法定节假日)',
        'workday_ds' => '工作日(单双周)',
        'workday_dx' => '工作日(大小周)',
        'workday_yl' => '工作日(周一至周六)',
        'weekend' => '周六周日',
        'everyweek' => '每周',
        'everymonth' => '每月'
    );
}

//读取本周是单还是双周
function get_week_of_year() {
    $datearr = getdate();
    $year = strtotime($datearr['year'] . '-1-1');
    $startdate = getdate($year);
    $firstweekday = 7 - $startdate['wday']; //获得第一周几天
    $yday = $datearr['yday'] + 1 - $firstweekday; //今年的第几天
    return ceil($yday / 7) + 1; //取到第几周
}

function get_frequency_name($frequency = 'day') {
    $arr = get_frequency_list();
    return isset($arr[$frequency]) ? $arr[$frequency] : '未知';
}

function init_default_category($user_id) {
    $framework = &get_instance('controller');
    $data = array(
        'income' => array(
            '薪资' => array('公司工资', 'SOHO接单', '加班收入', '奖金'),
            '投资' => array('股票', '基金', '分红', '利息'),
            '其它' => array('发票中奖', '博彩收入', '其它'),
        ),
        'expense' => array(
            '衣' => array('购衣费', '化妆品', '洗衣费用', '箱包', '饰品'),
            '食' => array('外出就餐', '工作餐', '买菜', '柴米油盐', '外卖', '零食', '小吃', '饮料', '水果', '烟酒茶'),
            '住' => array('水电气费', '房租', '物业费'),
            '行' => array('停车费', '汽油费用', '公共交通', '的士费用', '汽车保养', '过路费', '年检保险', '违章罚款', '汽车修理'),
            '教育' => array('书籍杂志', '文具费用', '考试费用', '培训费用', '学杂费用'),
            '娱乐' => array('旅游度假', '休闲放松', '博彩支出', '健身运动', '宠物饲养'),
            '医疗' => array('诊疗费', '药品费', '健康食品'),
            '其它' => array('话费', '网费', '电器用品', '生活用品', '洗衣费用', '保险费用', '税收费用', '交际费用', '孝敬长辈', '捐款捐赠', '坏账损失'),
        )
    );
    $time = time();
    foreach ($data as $m => $n) {
        $index = 1;
        $sql = array();
        foreach ($n as $u => $v) {
            $id = $framework->db->insert("{pre}category", array('user_id' => $user_id, 'father_id' => 0, 'name' => $u, 'system' => 1, 'type' => $m, 'weigh' => $index, 'createtime' => $time, 'modifytime' => $time, 'state' => 1));
            foreach ($v as $i => $j) {
                //$framework->db->insert("{pre}category", array('user_id' => $user_id, 'father_id' => $id, 'name' => $j, 'system' => 1, 'type' => $m, 'weigh' => $i + 1, 'createtime' => $time, 'modifytime' => $time, 'state' => 1));
                $i++;
                $sql[] = "('{$user_id}', '{$id}', '{$j}', 1, '{$m}', {$i}, {$time}, {$time}, 1)";
            }
            $index++;
        }
        if ($sql) {
            $framework->db->query("INSERT INTO {pre}category(user_id, father_id, name, system, type, weigh, createtime, modifytime, state) VALUES " . implode(', ', $sql));
        }
    }
    return true;
}

function get_day_after_seconds($time = null) {
    $time = $time ? $time : time();
    $arr = explode(":", date("H:i:s", $time));
    return $arr[0] * 3600 + $arr[1] * 60 + $arr[2];
}